package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.TMStatMfdCriteriaMapper;
import cc.rengu.igas.momp.common.dao.impl.TMStatMfdCriteriaMapperImpl;
import cc.rengu.igas.momp.common.entity.TMStatMfdCriteria;
import cc.rengu.igas.momp.common.enums.QueryTypeEnum;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.bean.MchntQuotaInfoBean;
import cc.rengu.igas.momp.facade.request.QueryMchntFeeTxnAmtLimitRequest;
import cc.rengu.igas.momp.facade.response.QueryMchntFeeTxnAmtLimitResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商户当前周期手续费优惠限额查询
 *
 * @author liujinan
 * @version 1.0.0
 * @date 2021/6/21 09:19
 */
public class QueryMchntFeeTxnAmtLimitService extends RadpService {

    /**
     * 法人机构号
     */
    private String globalInstId;
    /**
     * 操作类型
     */
    private String globalQueryType;
    /**
     * 操作人
     */
    private String globalQueryId;
    /**
     * 操作角色
     */
    private String globalQueryRole;
    /**
     * 当前系统日期
     */
    private String globalTimeStamp;
    /**
     * 营销活动商户编号
     */
    private String globalMchntNo;
    /**
     * 营销活动商户名称
     */
    private String globalMchntName;
    /**
     * 交易日期
     */
    private String globalTxnDate;
    /**
     * 操作员所属法人机构
     */
    private String globalQueryOrgId;

    @Override
    protected int bizInit(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {
            QueryMchntFeeTxnAmtLimitRequest queryMchntFeeTxnAmtLimitRequest = new QueryMchntFeeTxnAmtLimitRequest();
            ConvertUtil.convertOutput(queryMchntFeeTxnAmtLimitRequest);

            QueryMchntFeeTxnAmtLimitResponse queryMchntFeeTxnAmtLimitResponse = new QueryMchntFeeTxnAmtLimitResponse();
            queryMchntFeeTxnAmtLimitResponse.setHeader(queryMchntFeeTxnAmtLimitRequest.getHeader());
            BizResponse<QueryMchntFeeTxnAmtLimitResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryMchntFeeTxnAmtLimitResponse);

            //报文检查
            messageValidation(queryMchntFeeTxnAmtLimitRequest);

            rglog.info("机构<{}>在<{}>由<{}>开始查询商户当前周期手续费优惠限额", globalInstId, globalTimeStamp, globalQueryId);

            // 服务调用
            BizResponse<QueryMchntFeeTxnAmtLimitResponse> bizResponseNew = queryMchntFeeTxnAmtLimitList(queryMchntFeeTxnAmtLimitRequest, queryMchntFeeTxnAmtLimitResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return CommonConstant.PROCESS_SUCCESS;
    }

    /**
     * 查询商户当前周期手续费优惠限额
     *
     * @param queryMchntFeeTxnAmtLimitRequest  商户当前周期手续费优惠限额查询接口请求对象
     * @param queryMchntFeeTxnAmtLimitResponse 商户当前周期手续费优惠限额查询接口应答对象
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.QueryMchntFeeTxnAmtLimitResponse> 营销活动商戶、用戶列表查询接口应答对象
     * @throws BizException 业务异常信息
     * @author liujinan
     * @date 2020/5/27 22:41
     */
    private BizResponse<QueryMchntFeeTxnAmtLimitResponse> queryMchntFeeTxnAmtLimitList(QueryMchntFeeTxnAmtLimitRequest queryMchntFeeTxnAmtLimitRequest, QueryMchntFeeTxnAmtLimitResponse queryMchntFeeTxnAmtLimitResponse) throws Exception {

        BizResponse<QueryMchntFeeTxnAmtLimitResponse> bizResponse = new BizResponse<>();

        List<MchntQuotaInfoBean> mchntQuotaInfoList = new ArrayList<>();
        //营销活动类型
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageIndex(Integer.parseInt(queryMchntFeeTxnAmtLimitRequest.getPageIndex()));
        pageInfo.setPageSize(Integer.parseInt(queryMchntFeeTxnAmtLimitRequest.getPageSize()));

        //银行人员查询
        if (QueryTypeEnum.BANK_QUERY_TYPE.getQueryTypeCode().equals(globalQueryType)) {
            rglog.info("银行人员开始查询商户当前周期手续费优惠限额,商户<{}> 商户名称<{}>", globalMchntNo, globalMchntName);
            //查询达标数据统计表
            List<Object> mchntQuotaInfoBeanList = getAllMchntQuotaInfoList(pageInfo, globalMchntNo, globalMchntName);

            if (null != mchntQuotaInfoBeanList && !mchntQuotaInfoBeanList.isEmpty()) {
                mchntQuotaInfoList = mchntQuotaInfoBeanList.stream().map(this::convertMchntQuotaInfo).collect(Collectors.toList());
            }

            queryMchntFeeTxnAmtLimitResponse.setMchntQuotaInfoList(mchntQuotaInfoList);
        } else if (QueryTypeEnum.MCHNT_QYERY_TYPE.getQueryTypeCode().equals(globalQueryType)) {
            //商户查询当前周期优惠限额
            String mchntNo = queryMchntFeeTxnAmtLimitRequest.getQueryId();
            rglog.info("商户人员开始查询商户当前周期手续费优惠限额，商户<{}>", mchntNo);
            List<Object> mchntQuotaInfoBeanList = getAllMchntQuotaInfoList(pageInfo, mchntNo, globalMchntName);

            if (null != mchntQuotaInfoBeanList && !mchntQuotaInfoBeanList.isEmpty()) {
                mchntQuotaInfoList = mchntQuotaInfoBeanList.stream().map(this::convertMchntQuotaInfo).collect(Collectors.toList());
            }

            queryMchntFeeTxnAmtLimitResponse.setMchntQuotaInfoList(mchntQuotaInfoList);
        } else {
            /* 其他查询角色不支持 */
            rglog.error("当前<{}>角色的查询用户<{}>无权限操作数据!", globalQueryRole, globalQueryType);
            throw new BizException(RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespCode(), RespCodeEnum.NO_AUTHORIZATION_TO_OPER_ERROR.getRespDesc());
        }


        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryMchntFeeTxnAmtLimitResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryMchntFeeTxnAmtLimitResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryMchntFeeTxnAmtLimitResponse.setPageIndex(queryMchntFeeTxnAmtLimitRequest.getPageIndex());
        queryMchntFeeTxnAmtLimitResponse.setPageSize(queryMchntFeeTxnAmtLimitRequest.getPageSize());
        queryMchntFeeTxnAmtLimitResponse.setTotalPage(String.valueOf(pageInfo.getTotalPage()));
        queryMchntFeeTxnAmtLimitResponse.setTotalRows(String.valueOf(pageInfo.getTotalRows()));

        bizResponse.setResult(queryMchntFeeTxnAmtLimitResponse);

        return bizResponse;
    }


    /**
     * 请求报文体内容检查
     *
     * @param queryMchntFeeTxnAmtLimitRequest 商户当前周期手续费优惠限额查询接口请求对象
     * @author liujinan
     * @date 2020/6/22 09:55
     */
    private void messageValidation(QueryMchntFeeTxnAmtLimitRequest queryMchntFeeTxnAmtLimitRequest) {

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getHeader().getTransDate())) {
            rglog.error("交易日期必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalTxnDate = queryMchntFeeTxnAmtLimitRequest.getHeader().getTransDate();
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getHeader().getTransTime())) {
            rglog.error("交易时间必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getHeader().getInstId())) {
            rglog.error("法人机构号必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalInstId = queryMchntFeeTxnAmtLimitRequest.getHeader().getInstId();
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getHeader().getTraceNo())) {
            rglog.error("流水号必须上送!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getQueryType())) {
            rglog.error("操作员类型为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryType = queryMchntFeeTxnAmtLimitRequest.getQueryType();
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getQueryId())) {
            rglog.error("操作员ID为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryId = queryMchntFeeTxnAmtLimitRequest.getQueryId();
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getQueryRole())) {
            rglog.error("操作员角色为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryRole = queryMchntFeeTxnAmtLimitRequest.getQueryRole();
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getQueryOrgId())) {
            rglog.error("操作员所属法人机构为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryOrgId = queryMchntFeeTxnAmtLimitRequest.getQueryOrgId();
        }

        if (!StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getMchntNo())) {
            globalMchntNo = queryMchntFeeTxnAmtLimitRequest.getMchntNo();
        }

        if (!StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getMchntName())) {
            globalMchntName = queryMchntFeeTxnAmtLimitRequest.getMchntName();
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getPageIndex())) {
            rglog.error("当前页数为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        if (StringUtil.isNullorEmpty(queryMchntFeeTxnAmtLimitRequest.getPageSize())) {
            rglog.error("页显示记录数为空!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        globalTimeStamp = new SimpleDateFormat(CommonConstant.TIMESTAMP_FORMAT).format(new Date());
    }


    /**
     * 获取商户当前周期优惠额度限额
     *
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2020/5/28 18:35
     */
    private List<Object> getAllMchntQuotaInfoList(PageInfo pageInfo, String mchntNo, String mchntName) throws Exception {

        List<Object> mchntQuotaInfoList = new ArrayList<>();
        TMStatMfdCriteria tmStatMfdCriteria = new TMStatMfdCriteria();
        tmStatMfdCriteria.setInstId(globalInstId);
        tmStatMfdCriteria.setPeriodStartDate(globalTxnDate);
        tmStatMfdCriteria.setPeriodEndDate(globalTxnDate);

        if (!StringUtil.isNullorEmpty(mchntNo)) {
            tmStatMfdCriteria.setMchntNo(mchntNo);
        }

        if (!StringUtil.isNullorEmpty(mchntName)) {
            tmStatMfdCriteria.setRemark1(mchntName);
        }
        TMStatMfdCriteriaMapper tmStatMfdCriteriaMapper = new TMStatMfdCriteriaMapperImpl();
        //不分页
        if (-1 == pageInfo.getPageIndex() || -1 == pageInfo.getPageSize()) {
            mchntQuotaInfoList = tmStatMfdCriteriaMapper.selectMchntQuotaInfoList(tmStatMfdCriteria);
        } else {
            PageResult tmMcMchntInfoPageInfo = tmStatMfdCriteriaMapper.selectMchntQuotaInfoPageList(tmStatMfdCriteria, pageInfo);
            if (null != tmMcMchntInfoPageInfo && null != tmMcMchntInfoPageInfo.getResult()) {
                mchntQuotaInfoList.addAll(tmMcMchntInfoPageInfo.getResult());
            }
        }
        return mchntQuotaInfoList;
    }


    /**
     * 商户当前周期优惠限额转换
     *
     * @param object 手续费减免达标数据统计表
     * @return cc.rengu.igas.momp.facade.bean.MchntQuotaInfoBean 商户当前周期优惠额度对象
     * @author liujinan
     * @date 2020/4/1 10:33
     */
    private MchntQuotaInfoBean convertMchntQuotaInfo(Object object) {

        MchntQuotaInfoBean mchntQuotaInfoBean = new MchntQuotaInfoBean();
        TMStatMfdCriteria tMStatMfdCriteria = (TMStatMfdCriteria) object;
        //商户名称
        mchntQuotaInfoBean.setMchntName(tMStatMfdCriteria.getRemark1());
        //商户号
        mchntQuotaInfoBean.setMchntNo(tMStatMfdCriteria.getMchntNo());
        //商户参与营销活动编号
        mchntQuotaInfoBean.setMcNo(tMStatMfdCriteria.getMcNo());
        //商户优惠额度
        mchntQuotaInfoBean.setMchntFeeTxnAmtLimit(tMStatMfdCriteria.getMrctDisUpLmtVal());
        //优惠额度结束日期
        String mrctDisUplmtEffDt = tMStatMfdCriteria.getMrctDisUplmtEffDt();
        if (mrctDisUplmtEffDt == null || "".equals(mrctDisUplmtEffDt))
            mrctDisUplmtEffDt = tMStatMfdCriteria.getPeriodEndDate();
        mchntQuotaInfoBean.setTxnAmtLimitEndDate(mrctDisUplmtEffDt);

        //存量商户达标标志
        mchntQuotaInfoBean.setCriteriaFlag(tMStatMfdCriteria.getCriteriaFlag());
        //商户新增标志
        mchntQuotaInfoBean.setNewMchntFlag(tMStatMfdCriteria.getNewMchntFlag());

        return mchntQuotaInfoBean;
    }
}
